package com.fs.chatx.module.chat.api;

import com.alibaba.fastjson.JSONObject;
import com.fs.chatx.core.api.R;
import com.fs.chatx.core.vo.EventData;
import com.fs.chatx.module.chat.entity.ChatMessage;
import com.fs.chatx.module.chat.entity.ChatSession;
import com.fs.chatx.module.chat.enums.MessageType;
import com.fs.chatx.module.chat.enums.RoleType;
import com.fs.chatx.module.chat.service.ChatMessageService;
import com.fs.chatx.module.chat.service.ChatSessionService;
import com.fs.chatx.module.chat.service.DeepseekService;
import com.fs.chatx.module.chat.vo.chat.ChatRequest;
import io.github.pigmesh.ai.deepseek.core.chat.ChatCompletionResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.util.Collections;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api")
public class ChatController
{

    @Autowired
    private ChatSessionService chatSessionService;

    @Autowired
    private ChatMessageService chatMessageService;

    @Autowired
    private DeepseekService deepseekService;

    @PostMapping(value = "/createSession")
    public R<String> createSession(@RequestBody ChatSession session)
    {
        String sessionId= chatSessionService.createChat(session);
        return R.success(sessionId);
    }

    // 新增删除会话接口
    @DeleteMapping("/deleteSession/{sessionId}")
    public R<String> deleteSession(@PathVariable String sessionId)
    {
        chatSessionService.removeChatSession(sessionId);
        return R.success("删除成功");
    }

    @PostMapping("/chatList")
    public R<List<ChatSession>> chatList(@RequestBody ChatSession session)
    {
        return R.success(chatSessionService.chatList(session.getUserId()));
    }


    @PostMapping(value = "/chatStream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ChatCompletionResponse> chatStream(@RequestBody ChatRequest request)
    {
        log.info("chatStream:{}",request);
        Assert.notNull(request.getContent(),"消息不能为空");
        ChatMessage msg= ChatMessage.builder()
                .agentId(request.getAgentId())
                .sessionId(request.getSessionId())
                .content(request.getContent())
                .model(request.getModel())
                .build();
        msg.setRole(RoleType.USER.getType());
        msg.setMessageType(MessageType.TEXT.getCode());
        JSONObject jsonData=new JSONObject();
        if (!CollectionUtils.isEmpty(request.getFiles()) ) {
            msg.setMessageType(MessageType.ATTACH.getCode());
            jsonData.put("files", request.getFiles());
        }
        boolean thinkingEnabled= request.isThinkingEnabled();
        jsonData.put("thinkingEnabled","0");
        if(thinkingEnabled){
            jsonData.put("thinkingEnabled","1");
        }
        msg.setJsonData(jsonData.toString());
        chatMessageService.addMessage(msg);
        log.info("chatStream msg:{}",msg);

        String prompt=request.getContent();
        StringBuffer thinkResponse = new StringBuffer();
        StringBuffer fullResponse = new StringBuffer();
        Flux<ChatCompletionResponse> response=  deepseekService.ragSearch(prompt)
                .doOnNext(r->{
                    String currentContent = r.choices().get(0).delta().content();
                    String reasoningContent = r.choices().get(0).delta().reasoningContent();
                   boolean think= reasoningContent!=null&&currentContent==null;
                   if(reasoningContent!=null&&reasoningContent.length()>0){
                       thinkResponse.append(reasoningContent);
                   }
                   if(currentContent!=null&&currentContent.length()>0){
                       fullResponse.append(currentContent);
                   }

                    String finishReason = r.choices().get(0).finishReason();
                    if ("stop".equals(finishReason)) {
                        log.info("Final answer: {}", fullResponse.toString());
                        msg.setRole(RoleType.ASSISTANT.getType());
                        msg.setContent(fullResponse.toString());
                        msg.setThinking(thinkResponse.toString());
                        msg.setMessageType(MessageType.TEXT.getCode());
                        msg.setJsonData(null);

                        chatMessageService.addMessage(msg);
                    }
                })
                .doOnError(error -> log.error("Streaming failed: {}", error.getMessage()))
                ;
        return response;
    }


    @PostMapping(value = "/sse", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<EventData> sse(@RequestBody ChatRequest request)
    {
        log.info("sse:{}",request);
        Assert.notNull(request.getContent(),"消息不能为空");
        ChatMessage msg= ChatMessage.builder()
                .agentId(request.getAgentId())
                .sessionId(request.getSessionId())
                .content(request.getContent())
                .model(request.getModel())
                .build();
        msg.setRole(RoleType.USER.getType());
        msg.setMessageType(MessageType.TEXT.getCode());
        JSONObject jsonData=new JSONObject();
        if (!CollectionUtils.isEmpty(request.getFiles()) ) {
            msg.setMessageType(MessageType.ATTACH.getCode());
            jsonData.put("files", request.getFiles());
        }
        boolean thinkingEnabled= request.isThinkingEnabled();
        jsonData.put("thinkingEnabled","0");
        if(thinkingEnabled){
            jsonData.put("thinkingEnabled","1");
        }
        msg.setJsonData(jsonData.toString());
        chatMessageService.addMessage(msg);
        log.info("chatStream msg:{}",msg);
        String prompt=request.getContent();
        StringBuffer thinkResponse = new StringBuffer();
        StringBuffer fullResponse = new StringBuffer();
        Flux<EventData> response=  deepseekService.ragSearch(prompt)
                .map(r->{
                    JSONObject eventData=new JSONObject();
                    String currentContent = r.choices().get(0).delta().content();
                    String reasoningContent = r.choices().get(0).delta().reasoningContent();
                    boolean think= reasoningContent!=null&&currentContent==null;
                    if(reasoningContent!=null&&reasoningContent.length()>0){
                        thinkResponse.append(reasoningContent);
                        eventData.put("reasoning_content",reasoningContent);
                    }
                    if(currentContent!=null&&currentContent.length()>0){
                        fullResponse.append(currentContent);
                        eventData.put("content",currentContent);
                    }

                    String finishReason = r.choices().get(0).finishReason();
                    if ("stop".equals(finishReason)) {
                        msg.setRole(RoleType.ASSISTANT.getType());
                        msg.setContent(fullResponse.toString());
                        msg.setThinking(thinkResponse.toString());
                        msg.setMessageType(MessageType.TEXT.getCode());
                        msg.setJsonData(null);
                        chatMessageService.addMessage(msg);
                        eventData.put("finishReason",finishReason);
                        eventData.put("thinkResponse",thinkResponse.toString());
                        eventData.put("fullResponse",fullResponse.toString());
                    }
                    return new EventData("message", eventData);
                })
                //.concatWithValues(new EventData("end", "Stream completed")) // 结束事件
                .onErrorResume(e ->
                        Flux.just(new EventData("error", "Streaming error: " + e.getMessage()))
                );
        return response;
    }




    // 获取会话历史
    @PostMapping("/historyMessage")
    public R<List<ChatMessage>> historyMessage(
        @RequestBody ChatMessage chatMessage
    ) {
        return R.success(chatMessageService.getHistory(chatMessage.getSessionId(), chatMessage));
    }


}
